package com.mwqi.ui.widget;

import com.mwqi.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * 按比例显示的布局
 * 
 * @author Administrator
 * 
 */
public class RatioLayout extends FrameLayout {
	// 宽和高的比例
	private float ratio = 0.0f;

	public RatioLayout(Context context) {
		this(context, null);
	}

	public RatioLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.RatioLayout);
		ratio = a.getFloat(R.styleable.RatioLayout_ratio, 0.0f);
		a.recycle();
	}

	public void setRatio(float f) {
		ratio = f;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// 获取父类传递过来的的模式
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		// MeasureSpec.getSize(widthMeasureSpec) 获取父类传递过来的大小
		// 与getMeasuredHeight()区别是? 解决ScrollView嵌套ListView和GridView冲突的方法

		int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft()
				- getPaddingRight();
		int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop()
				- getPaddingBottom();
		// 宽是精确的 makeMeasureSpec测量
		if (widthMode == MeasureSpec.EXACTLY
				&& heightMode != MeasureSpec.EXACTLY && ratio != 0.0f) {
			height = (int) (width / ratio + 0.5f);
			/**
			 * 后加上 MeasureSpec.makeMeasureSpec(height)---重新设置一个高度
			 * 与setMeasuredDimension(measuredWidth, measuredHeight);区别
			 **/
			heightMeasureSpec = MeasureSpec
					.makeMeasureSpec(height + getPaddingTop()
							+ getPaddingBottom(), MeasureSpec.EXACTLY);
		} else if (widthMode != MeasureSpec.EXACTLY
				&& heightMode == MeasureSpec.EXACTLY && ratio != 0.0f) {
			// 高是精确的
			width = (int) (height * ratio + 0.5f);
			widthMeasureSpec = MeasureSpec
					.makeMeasureSpec(width + getPaddingLeft()
							+ getPaddingRight(), MeasureSpec.EXACTLY);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);// --最后把参数传递给super
																// 让父类去测量
	}
}
